# frozen_string_literal: true

class RuleVersion < ApplicationRecord
  include Sortable
  belongs_to :rule

  validates :rule_id, presence: true
  validates :schema, presence: true
  validates :content, presence: true

  before_create :generate_version, :effective_from_now

  scope :version_asc, -> { asc_by :version }
  scope :version_desc, -> { desc_by :version }

  private

  def generate_version
    self.version = self.class.where(rule: rule).count.next
  end

  def effective_from_now
    self.start_time ||= Time.zone.now
  end
end
